#include "parkinginfowidget.h"
#include "ui_parkinginfowidget.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>

ParkingInfoWidget::ParkingInfoWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParkingInfoWidget)
{
    ui->setupUi(this);
    initWindow();
}

ParkingInfoWidget::~ParkingInfoWidget()
{
    delete ui;
}

/**
 * @brief 设置选中记录的ID
 * @param id
 */
void ParkingInfoWidget::setSelectedId(int id)
{
    this->selectedId = id;
    qDebug() << "selectedId::" << this->selectedId;
    //判断是新增车位信息还是修改车位信息
    //如果是修改车位信息
    if (this->selectedId > 0)
    {
        //获取选中的车位信息，填充至前端
        qDebug() << "selectedId::" << this->selectedId;
        QSqlQuery query;
        query.prepare("SELECT position, type, can_charge, size FROM parking WHERE id = :id");
        query.bindValue(":id", this->selectedId);
        if (!query.exec())
        {
            qDebug() << query.lastError();
        }
        else
        {
            if (query.next())
            {
                QString position = query.value(0).toString();
                int type = query.value(1).toInt();
                int canCharge = query.value(2).toInt();
                int size = query.value(3).toInt();

                ui->edit_position->setText(position);
                ui->cb_type->setCurrentIndex(type);
                ui->cb_can_charge->setCurrentIndex(canCharge);
                ui->cb_size->setCurrentIndex(size);
            }

        }
    }
}

/**
 * @brief 初始化窗体
 */
void ParkingInfoWidget::initWindow()
{
    this->setWindowTitle("车位信息");

    ui->cb_type->addItem("地上");
    ui->cb_type->addItem("楼层");
    ui->cb_can_charge->addItem("不可充电");
    ui->cb_can_charge->addItem("可充电");
    ui->cb_size->addItem("小");
    ui->cb_size->addItem("大");
}

/**
 * @brief 保存
 */
void ParkingInfoWidget::on_btn_save_clicked()
{
    QString position = ui->edit_position->text();
    QString type = ui->cb_type->currentText();
    QString canCharge = ui->cb_can_charge->currentText();
    QString size = ui->cb_size->currentText();

    qDebug() << "车位位置：" << position
             << "\n车位类型：" << type
             << "\n车位可充电：" << canCharge
             << "\n车位大小：" << size;

    QSqlQuery query;
    query.prepare("INSERT INTO parking (position, type, can_charge, size, status) VALUES (:position, :type, :can_charge, :size, :status)");
    query.bindValue(":position", position);
    query.bindValue(":type", type);
    query.bindValue(":can_charge", canCharge);
    query.bindValue(":size", size);
    query.bindValue(":status", "可用"); //车位状态：可用
    if (!query.exec())
    {
        qDebug()<<query.lastError();
        QMessageBox::warning(this, tr("错误"), tr("保存失败"), QMessageBox::Ok);
    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("保存成功"), QMessageBox::Ok);
    }

}
